package com.sxj.corejava.code12_线程;

/**
 * @author 石小俊
 * @date 2025年02月24日
 */
public class Test06_线程间的通信 {

    public static void main(String[] args) {
        Object obj = new Object();
        WaitThread t1 = new WaitThread(obj, "线程1");
        WaitThreadTwo t2 = new WaitThreadTwo(obj, "线程2");
        t1.start();
        t2.start();

        Object obj2 = new Object();
        NotifyThread notifyThread = new NotifyThread(obj, "notify线程");
        notifyThread.start();


//        NotifyAllThread notifyAllThread = new NotifyAllThread(obj,"notifyAll线程");
//        notifyAllThread.start();
    }

}

class WaitThread extends Thread {
    private Object obj;
    private String name;

    public WaitThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            try {
                // 可以设置等待时间,到时间后自动唤醒
//                obj.wait(3000);
                // 也可以不设置等待时间,表示只能等待其他线程唤醒
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + "执行完成");
        }
    }
}

class WaitThreadTwo extends Thread {
    private Object obj;
    private String name;

    public WaitThreadTwo(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + "执行完成");
        }
    }
}

class NotifyThread extends Thread {
    private Object obj;
    private String name;

    public NotifyThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            // 随机唤醒对象的等待池中的一个线程
            obj.notify();
            System.out.println(name + "已经随机唤醒了等待吃中的某一个线程");
        }
    }
}

class NotifyAllThread extends Thread {
    private Object obj;
    private String name;

    public NotifyAllThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            // 唤醒对象等待池中的所有线程
            obj.notifyAll();
            System.out.println(name + "已经随机唤醒了等待吃中的某一个线程");
        }
    }
}
